import * as qiniu from 'qiniu'
import * as request from 'request'
import * as uid from 'uid'
import * as fs from 'fs'
import * as path from 'path'
import * as http from 'http'
import { delay } from './../utility'
import { clearTimeout } from 'timers';
import { stringify } from 'querystring';
// import { Readable, PassThrough } from 'stream'

const ACCESS_KEY = 'hdTc-x9-BbHPheZ1-pCyjWMAf0OJoPVvTj9WTy9G';
const SECRET_KEY = 'Rn7Qdtof27Dg3QX4-JkOuhj3X6LYdkL2DXMU3-y5'
const BUCKET = 'jigi-imgs';
const QINIU_URL = 'https://oe5s738zx.qnssl.com';

qiniu.conf.ACCESS_KEY = ACCESS_KEY
qiniu.conf.SECRET_KEY = SECRET_KEY
var options = { scope: BUCKET };
var mac = new qiniu.auth.digest.Mac(qiniu.conf.ACCESS_KEY, qiniu.conf.SECRET_KEY);
var putPolicy = new qiniu.rs.PutPolicy(options);
var uploadToken = putPolicy.uploadToken(mac);

let qConfig = new qiniu.conf.Config()
var formUploader = new qiniu.form_up.FormUploader(qConfig);
var putExtra = new qiniu.form_up.PutExtra();
var bucketManager = new qiniu.rs.BucketManager(mac, qConfig);


export async function copyImagesFromSkyToQiniu(imageList: Array<string>): Promise<Array<string>> {
    if (!imageList || !Array.isArray(imageList) || !imageList.length) return [];
    var results = [];
    let set = new Set(imageList);
    imageList = Array.from(set);//去重
    console.time('上传图片并压缩')
    for (let url of imageList) {
        let newUrl = url;
        try {
            newUrl = await upload(url);
        } catch (error) {
            console.log(`Error occurs when convert image to Qiniu ${JSON.stringify(error)}`);
        }
        results.push(newUrl)
        await delay(800);
    }
    console.timeEnd('上传图片并压缩')
    return results;
}

export async function upload(skyUrl: string) {
    try {
        let res = await uploadImage(skyUrl);
        if (!res) return skyUrl;
        let key = res;
        let newKey = `q_50_${key}`
        await compressImage(key, newKey);
        await deleteImageAfterOneDay(newKey)
        return `${QINIU_URL}/${newKey}`;
    } catch (error) {
        return skyUrl;
    }

}

/** 从顺凯的服务器拉图片，上传到七牛去
 * @param {string}  skyUrl - 顺凯的地址
 */
export async function uploadImage(skyUrl: string) {
    skyUrl = encodeURI(skyUrl)
    try {
        return new Promise((resolve) => {
            let key = uid(20) + '.jpg';
            let imgPath = path.join(__dirname, './../../temp/' + key);
            let stream = fs.createWriteStream(imgPath);
            stream.on('close', function () {
                formUploader.putFile(uploadToken, key, imgPath, putExtra, function (respErr, respBody, respInfo) {
                    if (respInfo.statusCode == 200) {
                        console.log('upload success');
                        resolve(key);
                    } else {
                        console.log('upload fail');
                        resolve(false);
                    }
                });
            })
            request(skyUrl).pipe(stream);
        });
    } catch (error) {
        console.log(`error happen at uploadImage function ${JSON.stringify(error)}`);
        return false;
    }
}


/** 压缩图片 */
export async function compressImage(key, newKey) {
    return new Promise((resolve, reject) => {
        try {
            var bucket = BUCKET;
            var host = BUCKET + ".qiniudn.com";
            // jigi-imgs.qiniudn.com
            var encodedEntryURI = qiniu.util.urlsafeBase64Encode(bucket + ":" + newKey);
            var signingStr = "/" + key + "?imageView2/3/w/1200/h/900/q/50|saveas/" + encodedEntryURI;

            var savePath = BUCKET + ".qiniudn.com/" + key + "?imageView2/3/w/1200/h/900/q/50|saveas/" + encodedEntryURI;
            var signed = qiniu.util.hmacSha1(new Buffer(savePath), SECRET_KEY);
            var signedSafe1 = qiniu.util.base64ToUrlSafe(signed);
            var imgUrl = signingStr + "/sign/" + ACCESS_KEY + ":" + signedSafe1;
            let req = http.get({ host: host, port: 80, path: imgUrl, timeout: 3000 }, function (res) {
                res.setEncoding('UTF-8');
                res.on('data', function (data) { });
                res.on('end', function () {
                    console.log(`压缩结束: ${newKey}`);
                    resolve();//结束
                });
                res.on('error', err => {
                    console.log(`${newKey} 压缩出错${JSON.stringify(err)}`);
                    reject(err);
                })
            });
            req.on('error', (err) => {
                reject(`压缩出错 request error ${JSON.stringify(err)}`)
            })
        } catch (error) {
            reject(`压缩出错 compressImage: something unknown happened ${JSON.stringify(error)}`)
        }

    });
}

export async function deleteImageAfterOneDay(key) {
    return new Promise((resolve, reject) => {
        bucketManager.deleteAfterDays(BUCKET, key, 1, function (err, respBody, respInfo) {
            if (err) reject(err);
            console.log('删除结束');
            resolve();
        });
    })

}